package com.terry.proxy.common;

import cn.hutool.json.JSONUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.NoArgsConstructor;

/**
 * 编码器
 *
 * @author allen
 * @date 2022/12/07
 */
@NoArgsConstructor
public class MsgEncoder extends MessageToByteEncoder<Msg> {


    @Override
    protected void encode(ChannelHandlerContext ctx, Msg msg, ByteBuf out) throws Exception {
        // 4 总数据长度，8 消息类型的长度 8+ 消息类型， 消息头长度， 消息头内容，
        int bodyLength = 4;

        byte[] typeBytes = msg.getType().getBytes();
        bodyLength += 4;
        bodyLength += typeBytes.length;

        byte[] headerBytes = JSONUtil.toJsonStr(msg.getHeader()).getBytes();
        bodyLength += 4;
        bodyLength += headerBytes.length;

        byte[] data = msg.getData();
        if (data != null) {
            bodyLength += data.length;
        }

        out.writeInt(bodyLength);
        out.writeInt(typeBytes.length);
        out.writeBytes(typeBytes);
        out.writeInt(headerBytes.length);
        out.writeBytes(headerBytes);
        if (data != null) {
            out.writeBytes(data);
        }
    }
}